#by:json
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import os.path

def sendMail(to,html='',attach=''):

    #创建一个带附件的实例
    msg = MIMEMultipart()


    #构造正文
    if html!='':

        body = MIMEText(html,'html','utf-8')
    else:
        body = MIMEText('(空内容)','html','utf-8')
    msg.attach(body)

    #附件
    if os.path.isfile(attach):

        #构造附件1
        att1 = MIMEText(open(attach, 'rb').read(), 'base64', 'utf-8')
        att1["Content-Type"] = 'application/octet-stream'
        att1["Content-Disposition"] = 'attachment; filename="access.log.txt"'#这里的filename可以任意写，写什么名字，邮件中显示什么名字
    else:
        att1= MIMEText('(附件为空)','html','utf-8')
    msg.attach(att1)
    #构造附件2
    '''
    att2 = MIMEText(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312')
    att2["Content-Type"] = 'application/octet-stream'
    att2["Content-Disposition"] = 'attachment; filename="123.txt"'
    msg.attach(att2)
    '''

    #加邮件头信息
    msg['subject'] = html[0:10]
    msg['from'] = 'lu_xiaofei@sina.cn'
    #msg['to'] = '1175995117@qq.com'
    msg['to'] = to

    #发送邮件
    try:
        server = smtplib.SMTP()
        server.connect('smtp.sina.com')
        server.login('lu_xiaofei@sina.cn','Q111111')#XXX为用户名，XXXXX为密码
        server.sendmail(msg['from'], msg['to'],msg.as_string())
        server.quit()
        print('发送成功')
    except Exception as e:
        print(str(e))